// import ArrayBufferLike from "typescript";

export class EncriptTool {
    encriptSign: string = "";
    encriptKey: string = "";
    setKeySign(key: string, sign: string) {
        this.encriptKey = key;
        this.encriptSign = sign;
    }

    str2Bytes(str: string): Uint8Array {
        const encoder = new TextEncoder();
        return encoder.encode(str);
    }

    checkIsEncripted(arrbuf: any, sign = this.encriptSign): boolean {
        if (!sign || !arrbuf || !(arrbuf instanceof ArrayBuffer)) {
            return false;
        }
        const bytes = new Uint8Array(arrbuf);
        for (let i = 0; i < sign.length; i++) {
            if (bytes[i] !== sign.charCodeAt(i)) {
                return false;
            }
        }
        return true;
    }

    encodeArrayBuffer(arrbuf: ArrayBufferLike, key = this.encriptKey, sign = this.encriptSign): ArrayBufferLike {
        if (!key || !sign || !arrbuf || !(arrbuf instanceof ArrayBuffer)) {
            return arrbuf;
        }
        const bytes = new Uint8Array(arrbuf);
        const keyBytes = this.str2Bytes(key);
        const signBytes = this.str2Bytes(sign);
        const result = new Uint8Array(bytes.length + signBytes.length);
        result.set(signBytes, 0);
        for (let i = 0; i < bytes.length; i++) {
            result[i + signBytes.length] = bytes[i] ^ keyBytes[i % keyBytes.length];
        }
        return result.buffer;
    }

    decodeArrayBuffer(arrbuf: ArrayBufferLike, key = this.encriptKey, sign = this.encriptSign): ArrayBufferLike {
        if (!this.checkIsEncripted(arrbuf, sign)) {
            return arrbuf;
        }
        const bytes = new Uint8Array(arrbuf);
        const signBytes = this.str2Bytes(sign);
        if (bytes.length < signBytes.length) {
            return arrbuf; // 不足以包含签名
        }
        for (let i = 0; i < signBytes.length; i++) {
            if (bytes[i] !== signBytes[i]) {
                return arrbuf; // 签名不匹配
            }
        }
        const keyBytes = this.str2Bytes(key);
        const result = new Uint8Array(bytes.length - signBytes.length);
        for (let i = 0; i < result.length; i++) {
            result[i] = bytes[i + signBytes.length] ^ keyBytes[i % keyBytes.length];
        }
        return result.buffer;
    }
}